package bb.lanxing.adapter;

import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class SimpleViewPagerAdapter extends FragmentPagerAdapter {
    private Context mAppContext;
    private List<PageInfo> mPageList;

    public SimpleViewPagerAdapter(Context context, FragmentManager fragmentManager) {
        super(fragmentManager);
        this.mAppContext = context;
    }

    public void addItem(PageInfo pageInfo) {
        if (this.mPageList == null) {
            this.mPageList = new ArrayList<>();
        }
        this.mPageList.add(pageInfo);
    }

    public void addItem(String str, Class<?> cls, Bundle bundle) {
        addItem(new PageInfo(str, cls, bundle));
    }

    @NonNull
    @Override
    public Fragment getItem(int i) {
        PageInfo pageInfo = this.mPageList.get(i);
        if (pageInfo.instance != null) {
            return pageInfo.instance;
        }
        return Fragment.instantiate(this.mAppContext, pageInfo.fragment.getName(), pageInfo.data);
    }

    @Override
    public CharSequence getPageTitle(int i) {
        return mPageList.get(i).title;
    }

    @Override
    public int getCount() {
        return mPageList.size();
    }

    @Override
    public void unregisterDataSetObserver(@NonNull DataSetObserver dataSetObserver) {
        super.unregisterDataSetObserver(dataSetObserver);
        List<PageInfo> list = this.mPageList;
        if (list != null) {
            for (PageInfo pageInfo : list) {
                pageInfo.instance = null;
            }
        }
    }

    public static class PageInfo {
        Bundle data;
        Class<?> fragment;
        Fragment instance;
        String title;

        public PageInfo(String str, Class<?> cls, Bundle bundle) {
            this.title = str;
            this.fragment = cls;
            this.data = bundle;
        }
    }
}
